package servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import ex.DatabaseException;
import ex.RatingException;

import service.UserService;
import util.RegexUtil;

public class UserProfile extends HttpServlet {
	UserService userService=new UserService();
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try{
			String who=request.getParameter("who");
			if(who!=null){
				if(who.equals("me"))	{
					HttpSession session = request.getSession();
					if(session!=null){					
						if(session.getAttribute("user")!=null){
							domain.User user=(domain.User)session.getAttribute("user");
							request.setAttribute("user", user);
						}
					}
				}
				else{
					if(RegexUtil.isParsableToInt(who)){
						long uid=Long.parseLong(who);
						domain.User user=userService.getUserByUid(uid);
						request.setAttribute("user", user);
					}
					else{
						response.sendRedirect("home");
					}
				}
			}
			else{
				response.sendRedirect("home");
			}
			
			if(request.getAttribute("user")!=null)		{
				RequestDispatcher dispatcher = request.getRequestDispatcher("jsp/user/user-show.jsp");
				if (dispatcher != null) dispatcher.forward(request, response);
			}
			else{
				response.sendRedirect("home");
			}
		}
		catch (DatabaseException e) {
			request.setAttribute("error", e.getMessage());
		}
		catch (Exception e) {
			request.setAttribute("error", "A general error occured");
		}
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

	}
}
